<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import uploadImage from '@/assets/upload-image.png'
import { filePictureset } from '@/apis/apis.js'
import { imageRegex } from '@/utils/utils.js'
import useGoodsStore from '@/stores/useGoodsStore.js'

const goodsStore = useGoodsStore()
const dialogVisible = ref(false) // 控制对话框开关
const image = ref(goodsStore.isEdit ? goodsStore.currentGoods.goods_image : '') // 选择图片地址
const fileList = ref([]) // 默认上传文件
const page = ref(1) // 分页值，获取第一页为1，以此类推
const pictureSet = ref([]) // 历史上传图片合集
const activeIndex = ref(0) // 选择历史上传图片索引值
const moreDisabled = ref(false) // 是否禁用加载更多按钮

const handleBeforeUpload = (rawFile) => {
  try {
    imageRegex({ imageName: rawFile.name, imageSize: rawFile.size })
  }
  catch (err) {
    console.error(err.message)
    return false
  }
} // 上传文件之前的钩子

const handleSuccess = (response, uploadFile, uploadFiles) => {
  ElMessage({ type: 'info', message: '图片文件上传成功', duration: 1000 })
  setTimeout(() => {
    fileList.value = []
  }, 1000)
  image.value = response.data.fileurl
  dialogVisible.value = false
} // 文件上传成功时的钩子

const getFilePictureset = async () => {
  const res = await filePictureset({ page: page.value })
  if (res.data.length <= 0) {
    moreDisabled.value = true
  }
  pictureSet.value = [...pictureSet.value, ...res.data]
} // 获取图片合集

const more = () => {
  page.value = page.value + 1
  getFilePictureset()
} // 加载更多

const handleClose = () => {
  page.value = 1
  pictureSet.value = []
  activeIndex.value = 0
  moreDisabled.value = false
}

const handleConfirm = () => {
  image.value = pictureSet.value[activeIndex.value] ? pictureSet.value[activeIndex.value].fileurl : ''
  dialogVisible.value = false
}

watch(dialogVisible, () => {
  if (dialogVisible.value) {
    getFilePictureset()
  }
})

defineExpose({
  image
})
</script>

<template>
  <el-image style="width: 100px; height: 100px; cursor: pointer;" :src="image ? image : uploadImage" fit="cover"
    @click="dialogVisible = true" />
  <el-dialog v-model="dialogVisible" title="上传或选择图片" width="1000" @close="handleClose">
    <div style="text-align: center;">
      <el-upload action="https://meituan.thexxdd.cn/cha/file/uploadfile" v-model:file-list="fileList" :limit="1"
        :on-success="handleSuccess" :before-upload="handleBeforeUpload">
        <template #trigger>
          <el-button type="primary">上传图片</el-button>
        </template>
        <template #tip>
          <div class="el-upload__tip">
            允许上传≤3MB且JPG、PNG、JPEG、WEBP格式的图片文件
          </div>
        </template>
      </el-upload>
    </div>
    <el-scrollbar height="400px" style="text-align: center;">
      <el-row :gutter="10" style="width: 100%;">
        <el-col style="position: relative; cursor: pointer;" :span="4" v-for="(item, index) in pictureSet"
          :key="item._id" @click="activeIndex = index">
          <img v-show="index === activeIndex" src="@/assets/xuanzhong.png"
            style="position: absolute; top: 0; right: 0; width: 15%; aspect-ratio: 1/1; z-index: 999;">
          <el-image style="width: 100%; aspect-ratio: 1/1;" :src="item.fileurl" fit="cover" />
        </el-col>
      </el-row>
      <el-button :type="!moreDisabled ? 'primary' : 'info'" text @click="more" :disabled="moreDisabled">{{ !moreDisabled
        ?
        '加载更多' : '全部加载完毕' }}</el-button>
    </el-scrollbar>
    <template #footer>
      <div>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="warning" @click="handleConfirm">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped></style>
